#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>

#define INT32 int
#define IPPING_RESULT_FILE "./result_ipping.txt"

#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

typedef struct _ipping{
	char state[64];
	char interface[256];
	char host[256];
	char repetitions[32];
	char timeout[32];
	char data_size[32];
	char dscp[32];
	int succ_cnt;
	int fail_cnt;
	int avg;
	int min;
	int max;
	int avg_dtl;
	int min_dtl;
	int max_dtl;
}IPPING_T;

static IPPING_T ipping={"None", "", "", "", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0};

void ipping_start()
{
	char cmd[128] = {0};

	//sprintf(cmd, "ping -c 5 -s 1024 -I enp0s8 -W 10 192.168.0.101 > %s", IPPING_RESULT_FILE);
	sprintf(cmd, "ping -c 2 -s 10240 -W 10 192.168.0.101 > %s", IPPING_RESULT_FILE);
	system(cmd);
}

INT32 ipping_load_result(char *file)
{
	FILE *fp = NULL;
	char buff[512] = {0};
	char pkt_send[32] = {0};
	char pkt_recv[32] = {0};
	char min[32] = {0};
	char avg[32] = {0};
	char max[32] = {0};
	int imin = 0;
	int iavg = 0;
	int imax = 0;

	fp = fopen(file, "r");
	if(fp == NULL)
		return 0;

	printf("<----- file = [%s] ----->\n", file);
	while(fgets(buff, sizeof(buff), fp)){
#if 1
		if(2 == sscanf(buff, "%[0-9] packets transmitted, %[0-9] *", pkt_send, pkt_recv)){
			printf("dbg---> send=[%s], recv=[%s]\n", pkt_send, pkt_recv);
			ipping.succ_cnt = atoi(pkt_recv);
			ipping.fail_cnt = atoi(pkt_send) - atoi(pkt_recv);
		}
#endif
		if( 3 == sscanf(buff, "%*[^=]= %[^/]/%[^/]/%[^/ ] *", min, avg, max)){
			printf("dbg---> a min=[%s], avg=[%s], max=[%s]\n", min, avg, max);
			imin = (int)round(atof(min));
			iavg = (int)round(atof(avg));
			imax = (int)round(atof(max));
			printf("dbg---> a imin=[%d], iavg=[%d], imax=[%d]\n", imin, iavg, imax);
			ipping.avg = iavg;
			ipping.min = imin;
			ipping.max = imax;
			ipping.avg_dtl = iavg;
			ipping.min_dtl = imin;
			ipping.max_dtl = imax;
		}
	}
	fclose(fp);
	
	return 0;
}

void ipping_print()
{
	printf("succ_cnt=[%d], fail_cnt=[%d]\n", ipping.succ_cnt, ipping.fail_cnt);
	printf("avg=[%d], min=[%d], max=[%d]\n", ipping.avg, ipping.min, ipping.max);
	printf("avg_dtl=[%d], min_dtl=[%d], max_dtl=[%d]\n", ipping.avg_dtl, ipping.min_dtl, ipping.max_dtl);
}


int main(int argc, char *argv[])
{
	int index;

	ipping_start();
	ipping_load_result(IPPING_RESULT_FILE);
	ipping_print();

	return 0;
}
